package com.iot.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.commonutils.utils.Result;
import com.iot.user.dtos.UpdatePwdDto;
import com.iot.user.entity.User;
import com.iot.user.mapper.UserMapper;
import com.iot.user.service.UpdatePwdService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UpdatePwdServiceImpl extends ServiceImpl<UserMapper, User> implements UpdatePwdService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Result updatePwd(UpdatePwdDto dto) {
        if (StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getNewpasswordone())
                || StringUtils.isEmpty(dto.getNewpasswordtwo())
        ) {
            return Result.error("密码不能为空");
        }
        //判断两次密码是否一致
        if (!dto.getNewpasswordone().equals(dto.getNewpasswordtwo())) {
            return Result.error("两次输入密码不一致,请重新输入");
        }
        String user_id = redisTemplate.opsForValue().get("USER_ID");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> userId = queryWrapper.eq("id", user_id);
        List<User> listUserId = list(userId);
        User user = listUserId.get(0);
        String password = user.getPassword();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (!password.equals(md5DigestAsHex)) {
            return Result.error("原始密码错误");
        }

        //修改密码进行加密
        String md5DigestAsHex1 = DigestUtils.md5DigestAsHex((dto.getNewpasswordone() + user.getSalt()).getBytes());

        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", user_id);
        User user1 = new User();
        user1.setPassword(md5DigestAsHex1);
        update(user1, wrapper);

        return Result.success("修改密码成功~");
    }
}
